import { createI18n } from 'vue-i18n'
import locale from '@/locale'

const LOCALE_KEY = 'locale';

// 语言列表
const list = []
const messages = {}

// 整理语言列表
void locale.forEach(lang => {
  list.push({ code: lang.name, name: lang.language })
  messages[lang.name] = lang
})

// 保存实例
const i18n = createI18n({
  // 默认第一个语言
  locale: localStorage.getItem(LOCALE_KEY) || list[0].code,
  messages
})

// 获取当前语言
const get = () => i18n.global.locale

// 设置语言
const set = code => {
  i18n.global.locale = code
  localStorage.setItem(LOCALE_KEY, code)
}

// 追加语言
const append = (name, locale) => {
  for (const key in locale) {
    messages[key][name] = locale[key]
  }
}

// 使用
const t = i18n.global.t
const tm = i18n.global.tm

// 命名空间
const space = name => {
  const callback = class {
    constructor(name) {
      this.name = name + '.'
    }

    t(...arge) {
      arge[0] = this.name + arge[0]
      return t(...arge)
    }

    tm = (...arge) => {
      arge[0] = this.name + arge[0]
      return tm(...arge)
    }
  }

  return new callback(name)
}

export default { i18n, list, get, set, append, t, tm, space }